<template>
  <div class="risk-control-page">
    <h1>风控管理</h1>
    <section class="risk-section">
      <h2>风控规则配置</h2>
      <div>
        <el-button type="primary" @click="openEditDialog()">新增规则</el-button>
        <el-table :data="ruleList" style="margin-top: 16px">
          <el-table-column prop="typeName" label="规则类型" width="160" />
          <el-table-column prop="paramText" label="参数" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'enabled' ? 'success' : 'info'">
                {{ scope.row.status === 'enabled' ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template #default="scope">
              <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button size="small" type="warning" @click="toggleStatus(scope.row)">
                {{ scope.row.status === 'enabled' ? '禁用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" @click="deleteRule(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog v-model="editDialogVisible" :title="editRule.id ? '编辑规则' : '新增规则'" width="500px">
        <el-form :model="editRule" label-width="100px">
          <el-form-item label="规则类型">
            <el-select v-model="editRule.type" placeholder="请选择规则类型" @change="onTypeChange">
              <el-option label="单日积分获取上限" value="daily_limit" />
              <el-option label="单IP注册上限" value="ip_register_limit" />
              <el-option label="任务完成频率" value="task_freq_limit" />
              <el-option label="连续签到天数" value="signin_days_limit" />
            </el-select>
          </el-form-item>
          <el-form-item label="参数设置">
            <div v-if="editRule.type === 'daily_limit'">
              <el-input-number v-model="editRule.limitValue" :min="1" :max="10000" placeholder="积分数量" />
              <span style="margin-left: 8px; color: #666;">积分/天</span>
            </div>
            <div v-else-if="editRule.type === 'ip_register_limit'">
              <el-input-number v-model="editRule.limitValue" :min="1" :max="100" placeholder="注册数量" />
              <span style="margin-left: 8px; color: #666;">个账号/天</span>
            </div>
            <div v-else-if="editRule.type === 'task_freq_limit'">
              <el-input-number v-model="editRule.limitValue" :min="1" :max="50" placeholder="完成次数" />
              <span style="margin-left: 8px; color: #666;">次/天</span>
            </div>
            <div v-else-if="editRule.type === 'signin_days_limit'">
              <el-input-number v-model="editRule.limitValue" :min="1" :max="365" placeholder="连续天数" />
              <span style="margin-left: 8px; color: #666;">天</span>
            </div>
            <div v-else>
              <el-input v-model="editRule.param" placeholder="请输入参数" />
            </div>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch v-model="editRule.status" active-value="enabled" inactive-value="disabled" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRule">保存</el-button>
        </template>
      </el-dialog>
    </section>
    <section class="risk-section">
      <h2>异常行为监控</h2>
      <div>
        <div class="filter-bar">
          <el-select v-model="monitorFilter.type" placeholder="异常类型" style="width: 150px; margin-right: 12px;">
            <el-option label="全部" value="" />
            <el-option label="积分异常获取" value="points_abnormal" />
            <el-option label="注册异常" value="register_abnormal" />
            <el-option label="任务异常" value="task_abnormal" />
          </el-select>
          <el-select v-model="monitorFilter.status" placeholder="处理状态" style="width: 120px; margin-right: 12px;">
            <el-option label="全部" value="" />
            <el-option label="待处理" value="pending" />
            <el-option label="已处理" value="processed" />
            <el-option label="已忽略" value="ignored" />
          </el-select>
          <el-date-picker v-model="monitorFilter.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px; margin-right: 12px;" />
          <el-button type="primary" @click="searchMonitor">查询</el-button>
          <el-button @click="resetMonitorFilter">重置</el-button>
        </div>
        <el-table :data="monitorList" style="margin-top: 16px">
          <el-table-column prop="userInfo" label="用户信息" width="180">
            <template #default="scope">
              <div>
                <div>{{ scope.row.userName }}</div>
                <div style="font-size: 12px; color: #999;">{{ scope.row.userPhone }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="异常类型" width="120">
            <template #default="scope">
              <el-tag :type="getMonitorTypeTag(scope.row.type)">{{ getMonitorTypeText(scope.row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="异常描述" />
          <el-table-column prop="triggerTime" label="触发时间" width="160" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button size="small" @click="viewMonitorDetail(scope.row)">查看详情</el-button>
              <el-dropdown v-if="scope.row.status === 'pending'">
                <el-button size="small" type="primary">
                  处理 <el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="processMonitor(scope.row, 'mark_processed')">
                      标记已处理
                    </el-dropdown-item>
                    <el-dropdown-item @click="processMonitor(scope.row, 'freeze_points')">
                      冻结积分账户
                    </el-dropdown-item>
                    <el-dropdown-item @click="processMonitor(scope.row, 'deduct_points')">
                      扣除异常积分
                    </el-dropdown-item>
                    <el-dropdown-item @click="processMonitor(scope.row, 'add_blacklist')">
                      加入黑名单
                    </el-dropdown-item>
                    <el-dropdown-item @click="processMonitor(scope.row, 'ignore')">
                      忽略异常
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="monitorPagination.current" v-model:page-size="monitorPagination.size" :total="monitorPagination.total" layout="total, sizes, prev, pager, next" style="margin-top: 16px; text-align: right;" />
      </div>
      <el-dialog v-model="monitorDetailVisible" title="异常详情" width="600px">
        <div v-if="currentMonitor">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户姓名">{{ currentMonitor.userName }}</el-descriptions-item>
            <el-descriptions-item label="用户手机">{{ currentMonitor.userPhone }}</el-descriptions-item>
            <el-descriptions-item label="异常类型">{{ getMonitorTypeText(currentMonitor.type) }}</el-descriptions-item>
            <el-descriptions-item label="触发时间">{{ currentMonitor.triggerTime }}</el-descriptions-item>
            <el-descriptions-item label="处理状态">{{ getStatusText(currentMonitor.status) }}</el-descriptions-item>
            <el-descriptions-item label="IP地址">{{ currentMonitor.ipAddress }}</el-descriptions-item>
            <el-descriptions-item label="异常描述" :span="2">{{ currentMonitor.description }}</el-descriptions-item>
            <el-descriptions-item label="详细信息" :span="2">{{ currentMonitor.detail }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <el-button @click="monitorDetailVisible = false">关闭</el-button>
          <el-dropdown v-if="currentMonitor?.status === 'pending'">
            <el-button type="primary">
              处理异常 <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="processMonitor(currentMonitor, 'mark_processed')">
                  标记已处理
                </el-dropdown-item>
                <el-dropdown-item @click="processMonitor(currentMonitor, 'freeze_points')">
                  冻结积分账户
                </el-dropdown-item>
                <el-dropdown-item @click="processMonitor(currentMonitor, 'deduct_points')">
                  扣除异常积分
                </el-dropdown-item>
                <el-dropdown-item @click="processMonitor(currentMonitor, 'add_blacklist')">
                  加入黑名单
                </el-dropdown-item>
                <el-dropdown-item @click="processMonitor(currentMonitor, 'ignore')">
                  忽略异常
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-dialog>
      <el-dialog v-model="processDialogVisible" :title="processDialogTitle" width="500px">
        <el-form :model="processForm" label-width="100px">
          <el-form-item label="处理方式">
            <el-radio-group v-model="processForm.action">
              <el-radio value="mark_processed">标记已处理</el-radio>
              <el-radio value="freeze_points">冻结积分账户</el-radio>
              <el-radio value="deduct_points">扣除异常积分</el-radio>
              <el-radio value="add_blacklist">加入黑名单</el-radio>
              <el-radio value="ignore">忽略异常</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="扣除积分" v-if="processForm.action === 'deduct_points'">
            <el-input-number v-model="processForm.deductPoints" :min="1" :max="10000" placeholder="请输入扣除积分数量" />
            <span style="margin-left: 8px; color: #666;">积分</span>
          </el-form-item>
          <el-form-item label="冻结时长" v-if="processForm.action === 'freeze_points'">
            <el-input-number v-model="processForm.freezeHours" :min="1" :max="720" placeholder="请输入冻结时长" />
            <span style="margin-left: 8px; color: #666;">小时</span>
          </el-form-item>
          <el-form-item label="黑名单类型" v-if="processForm.action === 'add_blacklist'">
            <el-radio-group v-model="processForm.blacklistType">
              <el-radio value="user">用户黑名单</el-radio>
              <el-radio value="ip">IP黑名单</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="处理备注">
            <el-input v-model="processForm.remark" type="textarea" :rows="3" placeholder="请输入处理备注（可选）" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmProcess">确定处理</el-button>
        </template>
      </el-dialog>
    </section>
    <section class="risk-section">
      <h2>黑名单管理</h2>
      <div>
        <el-tabs v-model="blacklistActiveTab">
          <el-tab-pane label="用户黑名单" name="user">
            <div class="tab-content">
              <el-button type="primary" @click="openBlacklistDialog('user')">添加用户黑名单</el-button>
              <el-table :data="userBlacklist" style="margin-top: 16px">
                <el-table-column prop="userName" label="用户姓名" width="120" />
                <el-table-column prop="userPhone" label="用户手机" width="150" />
                <el-table-column prop="reason" label="加入原因" />
                <el-table-column prop="addTime" label="加入时间" width="160" />
                <el-table-column prop="operator" label="操作人" width="100" />
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button size="small" type="danger" @click="removeFromBlacklist('user', scope.row)">移除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane label="设备/IP黑名单" name="device">
            <div class="tab-content">
              <el-button type="primary" @click="openBlacklistDialog('device')">添加设备/IP黑名单</el-button>
              <el-table :data="deviceBlacklist" style="margin-top: 16px">
                <el-table-column prop="type" label="类型" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.type === 'ip' ? 'warning' : 'info'">
                      {{ scope.row.type === 'ip' ? 'IP地址' : '设备ID' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="value" label="值" width="150" />
                <el-table-column prop="reason" label="加入原因" />
                <el-table-column prop="addTime" label="加入时间" width="160" />
                <el-table-column prop="operator" label="操作人" width="100" />
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button size="small" type="danger" @click="removeFromBlacklist('device', scope.row)">移除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-dialog v-model="blacklistDialogVisible" :title="blacklistDialogTitle" width="500px">
        <el-form :model="blacklistForm" label-width="100px">
          <el-form-item label="类型" v-if="blacklistActiveTab === 'device'">
            <el-radio-group v-model="blacklistForm.type">
              <el-radio value="ip">IP地址</el-radio>
              <el-radio value="device">设备ID</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="blacklistActiveTab === 'user' ? '用户手机' : '值'">
            <el-input v-model="blacklistForm.value" :placeholder="blacklistActiveTab === 'user' ? '请输入用户手机号' : '请输入IP地址或设备ID'" />
          </el-form-item>
          <el-form-item label="加入原因">
            <el-input v-model="blacklistForm.reason" type="textarea" :rows="3" placeholder="请输入加入黑名单的原因" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="blacklistDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addToBlacklist">确定</el-button>
        </template>
      </el-dialog>
    </section>
    <section class="risk-section">
      <h2>风控日志</h2>
      <div>
        <div class="filter-bar">
          <el-select v-model="logFilter.eventType" placeholder="事件类型" style="width: 150px; margin-right: 12px;">
            <el-option label="全部" value="" />
            <el-option label="规则触发" value="rule_trigger" />
            <el-option label="黑名单操作" value="blacklist_operation" />
            <el-option label="异常处理" value="abnormal_process" />
            <el-option label="系统告警" value="system_alert" />
          </el-select>
          <el-select v-model="logFilter.level" placeholder="日志级别" style="width: 120px; margin-right: 12px;">
            <el-option label="全部" value="" />
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
          <el-date-picker v-model="logFilter.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px; margin-right: 12px;" />
          <el-button type="primary" @click="searchLog">查询</el-button>
          <el-button @click="resetLogFilter">重置</el-button>
          <el-button type="success" @click="exportLog">导出日志</el-button>
        </div>
        <el-table :data="logList" style="margin-top: 16px">
          <el-table-column prop="timestamp" label="时间" width="160" />
          <el-table-column prop="eventType" label="事件类型" width="120">
            <template #default="scope">
              <el-tag :type="getLogEventTypeTag(scope.row.eventType)">{{ getLogEventTypeText(scope.row.eventType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="level" label="级别" width="80">
            <template #default="scope">
              <el-tag :type="getLogLevelTag(scope.row.level)" size="small">{{ getLogLevelText(scope.row.level) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="事件描述" />
          <el-table-column prop="operator" label="操作人" width="100" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button size="small" @click="viewLogDetail(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="logPagination.current" v-model:page-size="logPagination.size" :total="logPagination.total" layout="total, sizes, prev, pager, next" style="margin-top: 16px; text-align: right;" />
      </div>
      <el-dialog v-model="logDetailVisible" title="日志详情" width="600px">
        <div v-if="currentLog">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="时间">{{ currentLog.timestamp }}</el-descriptions-item>
            <el-descriptions-item label="事件类型">{{ getLogEventTypeText(currentLog.eventType) }}</el-descriptions-item>
            <el-descriptions-item label="日志级别">{{ getLogLevelText(currentLog.level) }}</el-descriptions-item>
            <el-descriptions-item label="操作人">{{ currentLog.operator }}</el-descriptions-item>
            <el-descriptions-item label="事件描述" :span="2">{{ currentLog.description }}</el-descriptions-item>
            <el-descriptions-item label="详细信息" :span="2">
              <pre style="white-space: pre-wrap; font-family: inherit;">{{ getLogRuleTypeText(currentLog.detail) }}</pre>
            </el-descriptions-item>
            <el-descriptions-item label="相关用户" v-if="currentLog.relatedUser" :span="2">{{ currentLog.relatedUser }}</el-descriptions-item>
            <el-descriptions-item label="IP地址" v-if="currentLog.ipAddress" :span="2">{{ currentLog.ipAddress }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <el-button @click="logDetailVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'

interface Rule {
  id: number
  type: string
  typeName: string
  limitValue?: number
  param?: string
  paramText: string
  status: 'enabled' | 'disabled'
}

interface MonitorItem {
  id: number
  userName: string
  userPhone: string
  type: string
  description: string
  triggerTime: string
  status: string
  ipAddress: string
  detail: string
  relatedUser?: string
}

interface MonitorFilter {
  type: string
  status: string
  dateRange: any[]
}

interface Pagination {
  current: number
  size: number
  total: number
}

const ruleList = ref<Rule[]>([
  { 
    id: 1, 
    type: 'daily_limit', 
    typeName: '单日积分获取上限',
    limitValue: 1000,
    paramText: '每日最多获取1000积分',
    status: 'enabled' 
  },
  { 
    id: 2, 
    type: 'ip_register_limit', 
    typeName: '单IP注册上限',
    limitValue: 5,
    paramText: '同一IP每日最多注册5个账号',
    status: 'disabled' 
  },
  { 
    id: 3, 
    type: 'task_freq_limit', 
    typeName: '任务完成频率',
    limitValue: 3,
    paramText: '同一任务每日最多完成3次',
    status: 'enabled' 
  }
])

const editDialogVisible = ref(false)
const editRule = ref<Partial<Rule>>({})

// 异常行为监控相关
const monitorList = ref<MonitorItem[]>([
  {
    id: 1,
    userName: '张三',
    userPhone: '138****1234',
    type: 'points_abnormal',
    description: '单日积分获取超过限制',
    triggerTime: '2024-01-15 14:30:25',
    status: 'pending',
    ipAddress: '192.168.1.100',
    detail: '用户张三在2024-01-15单日获取积分1500，超过设定的1000积分上限'
  },
  {
    id: 2,
    userName: '李四',
    userPhone: '139****5678',
    type: 'register_abnormal',
    description: '同一IP注册账号过多',
    triggerTime: '2024-01-15 10:15:30',
    status: 'processed',
    ipAddress: '192.168.1.101',
    detail: 'IP地址192.168.1.101在24小时内注册了8个账号，超过设定的5个上限'
  },
  {
    id: 3,
    userName: '王五',
    userPhone: '137****9012',
    type: 'task_abnormal',
    description: '任务完成频率异常',
    triggerTime: '2024-01-14 16:45:12',
    status: 'ignored',
    ipAddress: '192.168.1.102',
    detail: '用户王五在1小时内完成了10次签到任务，频率异常'
  }
])

const monitorFilter = ref<MonitorFilter>({
  type: '',
  status: '',
  dateRange: []
})

const monitorPagination = ref<Pagination>({
  current: 1,
  size: 10,
  total: 3
})

const monitorDetailVisible = ref(false)
const currentMonitor = ref<MonitorItem | null>(null)

// 黑名单管理相关
interface BlacklistItem {
  id: number
  type?: string
  value: string
  userName?: string
  userPhone?: string
  reason: string
  addTime: string
  operator: string
}

const blacklistActiveTab = ref('user')
const userBlacklist = ref<BlacklistItem[]>([
  {
    id: 1,
    value: '138****1234',
    userName: '张三',
    userPhone: '138****1234',
    reason: '恶意刷积分',
    addTime: '2024-01-10 09:30:15',
    operator: '管理员'
  },
  {
    id: 2,
    value: '139****5678',
    userName: '李四',
    userPhone: '139****5678',
    reason: '批量注册账号',
    addTime: '2024-01-08 14:20:30',
    operator: '风控员'
  }
])

const deviceBlacklist = ref<BlacklistItem[]>([
  {
    id: 1,
    type: 'ip',
    value: '192.168.1.100',
    reason: '恶意IP，频繁注册',
    addTime: '2024-01-12 11:45:20',
    operator: '系统'
  },
  {
    id: 2,
    type: 'device',
    value: 'device_abc123',
    reason: '异常设备行为',
    addTime: '2024-01-09 16:30:45',
    operator: '管理员'
  }
])

const blacklistDialogVisible = ref(false)
const blacklistForm = ref({
  type: 'ip',
  value: '',
  reason: ''
})

const blacklistDialogTitle = computed(() => {
  return blacklistActiveTab.value === 'user' ? '添加用户黑名单' : '添加设备/IP黑名单'
})

const typeNameMap = {
  'daily_limit': '单日积分获取上限',
  'ip_register_limit': '单IP注册上限',
  'task_freq_limit': '任务完成频率',
  'signin_days_limit': '连续签到天数'
}

function getParamText(rule: Rule): string {
  if (rule.type === 'daily_limit') {
    return `每日最多获取${rule.limitValue}积分`
  } else if (rule.type === 'ip_register_limit') {
    return `同一IP每日最多注册${rule.limitValue}个账号`
  } else if (rule.type === 'task_freq_limit') {
    return `同一任务每日最多完成${rule.limitValue}次`
  } else if (rule.type === 'signin_days_limit') {
    return `连续签到最多${rule.limitValue}天`
  }
  return rule.param || ''
}

function onTypeChange() {
  editRule.value.limitValue = undefined
  editRule.value.param = ''
}

function openEditDialog(rule?: Rule) {
  if (rule) {
    editRule.value = { ...rule }
  } else {
    editRule.value = { type: '', limitValue: undefined, param: '', status: 'enabled' }
  }
  editDialogVisible.value = true
}

function saveRule() {
  if (!editRule.value.type) {
    ElMessage.warning('请选择规则类型')
    return
  }
  
  if (editRule.value.limitValue === undefined && !editRule.value.param) {
    ElMessage.warning('请设置参数')
    return
  }

  const newRule: Partial<Rule> = {
    type: editRule.value.type,
    typeName: typeNameMap[editRule.value.type as keyof typeof typeNameMap],
    limitValue: editRule.value.limitValue,
    param: editRule.value.param,
    status: editRule.value.status
  }

  if (editRule.value.id) {
    // 编辑
    const idx = ruleList.value.findIndex(r => r.id === editRule.value.id)
    if (idx > -1) {
      ruleList.value[idx] = { ...ruleList.value[idx], ...newRule }
      ruleList.value[idx].paramText = getParamText(ruleList.value[idx])
    }
    ElMessage.success('编辑成功')
  } else {
    // 新增
    const newId = Math.max(...ruleList.value.map(r => r.id), 0) + 1
    const ruleToAdd: Rule = {
      id: newId,
      type: newRule.type!,
      typeName: newRule.typeName!,
      limitValue: newRule.limitValue,
      param: newRule.param,
      paramText: getParamText({ ...newRule, id: newId } as Rule),
      status: newRule.status!
    }
    ruleList.value.push(ruleToAdd)
    ElMessage.success('新增成功')
  }
  editDialogVisible.value = false
}

function toggleStatus(rule: Rule) {
  rule.status = rule.status === 'enabled' ? 'disabled' : 'enabled'
  ElMessage.success('状态已更新')
}

function deleteRule(rule: Rule) {
  ElMessageBox.confirm('确定要删除该规则吗？', '提示', { type: 'warning' })
    .then(() => {
      ruleList.value = ruleList.value.filter(r => r.id !== rule.id)
      ElMessage.success('删除成功')
    })
}

// 异常行为监控相关函数
function getMonitorTypeText(type: string): string {
  const typeMap: Record<string, string> = {
    'points_abnormal': '积分异常获取',
    'register_abnormal': '注册异常',
    'task_abnormal': '任务异常'
  }
  return typeMap[type] || type
}

function getMonitorTypeTag(type: string): string {
  const tagMap: Record<string, string> = {
    'points_abnormal': 'danger',
    'register_abnormal': 'warning',
    'task_abnormal': 'info'
  }
  return tagMap[type] || 'info'
}

function getStatusText(status: string): string {
  const statusMap: Record<string, string> = {
    'pending': '待处理',
    'processed': '已处理',
    'ignored': '已忽略'
  }
  return statusMap[status] || status
}

function getStatusTag(status: string): string {
  const tagMap: Record<string, string> = {
    'pending': 'warning',
    'processed': 'success',
    'ignored': 'info'
  }
  return tagMap[status] || 'info'
}

function searchMonitor() {
  // 这里可以添加实际的搜索逻辑
  ElMessage.success('查询完成')
}

function resetMonitorFilter() {
  monitorFilter.value = {
    type: '',
    status: '',
    dateRange: []
  }
  ElMessage.success('筛选条件已重置')
}

function viewMonitorDetail(monitor: MonitorItem) {
  currentMonitor.value = monitor
  monitorDetailVisible.value = true
}

function processMonitor(monitor: MonitorItem, action: string) {
  // 直接处理或打开处理弹窗
  if (action === 'mark_processed' || action === 'ignore') {
    // 简单操作直接处理
    ElMessageBox.confirm(`确定要${action === 'mark_processed' ? '标记已处理' : '忽略'}这个异常吗？`, '提示', { type: 'warning' })
      .then(() => {
        monitor.status = action === 'mark_processed' ? 'processed' : 'ignored'
        monitor.detail = action === 'mark_processed' ? '异常行为已标记为已处理。' : '异常行为已忽略。'
        ElMessage.success('操作成功')
        if (monitorDetailVisible.value) {
          monitorDetailVisible.value = false
        }
      })
  } else {
    // 复杂操作打开处理弹窗
    currentProcessMonitor.value = monitor
    processForm.value.action = action
    processDialogVisible.value = true
  }
}

// 黑名单管理相关函数
function openBlacklistDialog(type: string) {
  blacklistActiveTab.value = type
  blacklistForm.value = {
    type: 'ip',
    value: '',
    reason: ''
  }
  blacklistDialogVisible.value = true
}

function addToBlacklist() {
  if (!blacklistForm.value.value || !blacklistForm.value.reason) {
    ElMessage.warning('请填写完整信息')
    return
  }

  const newItem: BlacklistItem = {
    id: Date.now(),
    type: blacklistActiveTab.value === 'device' ? blacklistForm.value.type : undefined,
    value: blacklistForm.value.value,
    userName: blacklistActiveTab.value === 'user' ? `用户${blacklistForm.value.value.slice(-4)}` : undefined,
    userPhone: blacklistActiveTab.value === 'user' ? blacklistForm.value.value : undefined,
    reason: blacklistForm.value.reason,
    addTime: new Date().toLocaleString(),
    operator: '当前用户'
  }

  if (blacklistActiveTab.value === 'user') {
    userBlacklist.value.push(newItem)
  } else {
    deviceBlacklist.value.push(newItem)
  }

  ElMessage.success('添加成功')
  blacklistDialogVisible.value = false
}

function removeFromBlacklist(type: string, item: BlacklistItem) {
  ElMessageBox.confirm('确定要移除这个黑名单吗？', '提示', { type: 'warning' })
    .then(() => {
      if (type === 'user') {
        userBlacklist.value = userBlacklist.value.filter(i => i.id !== item.id)
      } else {
        deviceBlacklist.value = deviceBlacklist.value.filter(i => i.id !== item.id)
      }
      ElMessage.success('移除成功')
    })
}

// 风控日志相关
interface LogItem {
  id: number
  timestamp: string
  eventType: string
  level: string
  description: string
  operator: string
  detail: string
  relatedUser?: string
  ipAddress?: string
}

interface LogFilter {
  eventType: string
  level: string
  dateRange: any[]
}

const logList = ref<LogItem[]>([
  {
    id: 1,
    timestamp: '2024-01-15 14:30:25',
    eventType: 'rule_trigger',
    level: 'high',
    description: '触发单日积分获取上限规则',
    operator: '系统',
    detail: '用户张三(138****1234)在2024-01-15单日获取积分1500，超过设定的1000积分上限。规则ID: 1，规则类型: daily_limit',
    relatedUser: '张三 (138****1234)',
    ipAddress: '192.168.1.100'
  },
  {
    id: 2,
    timestamp: '2024-01-15 10:15:30',
    eventType: 'blacklist_operation',
    level: 'medium',
    description: '添加用户到黑名单',
    operator: '管理员',
    detail: '将用户李四(139****5678)添加到用户黑名单，原因：批量注册账号',
    relatedUser: '李四 (139****5678)'
  },
  {
    id: 3,
    timestamp: '2024-01-14 16:45:12',
    eventType: 'abnormal_process',
    level: 'low',
    description: '处理异常行为',
    operator: '风控员',
    detail: '处理用户王五的任务完成频率异常，状态更新为已处理',
    relatedUser: '王五 (137****9012)'
  },
  {
    id: 4,
    timestamp: '2024-01-14 09:20:00',
    eventType: 'system_alert',
    level: 'high',
    description: '系统检测到异常IP访问',
    operator: '系统',
    detail: '检测到IP地址192.168.1.200在短时间内进行了大量异常操作，已自动加入IP黑名单',
    ipAddress: '192.168.1.200'
  }
])

const logFilter = ref<LogFilter>({
  eventType: '',
  level: '',
  dateRange: []
})

const logPagination = ref<Pagination>({
  current: 1,
  size: 10,
  total: 4
})

const logDetailVisible = ref(false)
const currentLog = ref<LogItem | null>(null)

// 异常处理弹窗相关
const processDialogVisible = ref(false)
const currentProcessMonitor = ref<MonitorItem | null>(null)
const processForm = ref({
  action: 'mark_processed',
  deductPoints: 0,
  freezeHours: 24,
  blacklistType: 'user',
  remark: ''
})

const processDialogTitle = computed(() => {
  return currentProcessMonitor.value ? `处理异常 - ${currentProcessMonitor.value.userName}` : '处理异常'
})

// 风控日志相关函数
function getLogEventTypeText(type: string): string {
  const typeMap: Record<string, string> = {
    'rule_trigger': '规则触发',
    'blacklist_operation': '黑名单操作',
    'abnormal_process': '异常处理',
    'system_alert': '系统告警'
  }
  return typeMap[type] || type
}

function getLogRuleTypeText(detail: string): string {
  // detail中如有规则类型英文，转为中文
  if (!detail) return ''
  return detail
    .replace(/规则类型: daily_limit/, '规则类型: 单日积分获取上限')
    .replace(/规则类型: ip_register_limit/, '规则类型: 单IP注册上限')
    .replace(/规则类型: task_freq_limit/, '规则类型: 任务完成频率')
    .replace(/规则类型: signin_days_limit/, '规则类型: 连续签到天数')
}

function getLogEventTypeTag(type: string): string {
  const tagMap: Record<string, string> = {
    'rule_trigger': 'warning',
    'blacklist_operation': 'danger',
    'abnormal_process': 'info',
    'system_alert': 'error'
  }
  return tagMap[type] || 'info'
}

function getLogLevelText(level: string): string {
  const levelMap: Record<string, string> = {
    'high': '高',
    'medium': '中',
    'low': '低'
  }
  return levelMap[level] || level
}

function getLogLevelTag(level: string): string {
  const tagMap: Record<string, string> = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'info'
  }
  return tagMap[level] || 'info'
}

function searchLog() {
  // 这里可以添加实际的搜索逻辑
  ElMessage.success('查询完成')
}

function resetLogFilter() {
  logFilter.value = {
    eventType: '',
    level: '',
    dateRange: []
  }
  ElMessage.success('筛选条件已重置')
}

function exportLog() {
  ElMessage.success('日志导出功能开发中...')
}

function viewLogDetail(log: LogItem) {
  currentLog.value = log
  logDetailVisible.value = true
}

function confirmProcess() {
  if (!currentProcessMonitor.value) return

  const monitor = currentProcessMonitor.value
  let newStatus: string
  let newDetail: string
  let newRelatedUser: string | undefined

  switch (processForm.value.action) {
    case 'freeze_points':
      newStatus = 'processed'
      newDetail = `积分账户已冻结${processForm.value.freezeHours}小时。${processForm.value.remark ? `备注：${processForm.value.remark}` : ''}`
      break
    case 'deduct_points':
      newStatus = 'processed'
      newDetail = `已扣除${processForm.value.deductPoints}积分。${processForm.value.remark ? `备注：${processForm.value.remark}` : ''}`
      break
    case 'add_blacklist':
      newStatus = 'processed'
      const blacklistTypeText = processForm.value.blacklistType === 'user' ? '用户黑名单' : 'IP黑名单'
      newDetail = `已加入${blacklistTypeText}。${processForm.value.remark ? `备注：${processForm.value.remark}` : ''}`
      newRelatedUser = `${monitor.userName} (${monitor.userPhone})`
      break
    default:
      return
  }

  monitor.status = newStatus
  monitor.detail = newDetail
  if (newRelatedUser) monitor.relatedUser = newRelatedUser

  ElMessage.success('处理成功')
  processDialogVisible.value = false
  if (monitorDetailVisible.value) {
    monitorDetailVisible.value = false
  }
}
</script>

<style scoped>
.risk-control-page {
  padding: 24px;
}
.risk-section {
  margin-bottom: 32px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
  padding: 20px;
}
.placeholder {
  color: #aaa;
  padding: 24px 0;
  text-align: center;
  font-size: 15px;
}
.filter-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
.tab-content {
  padding-top: 16px;
}
</style> 